<template>
  <div class="page">
    <!-- 图片区域 -->
    <div class="preview">
      <img
        :src="imageUrl"
        alt=""
        class="preview-image"
        v-if="taskDetail.status === TaskType.SUCCESS && !isSubmitting" />
      <div class="error" v-if="taskDetail.status === TaskType.FAIL && !isSubmitting">
        <img src="@/assets/photoframe/error.png" alt="" class="error-image" />
        <p>Generation failed</p>
      </div>
      <div class="loading-place" v-if="isSubmitting">
        <ProgressNumber ref="progressComponent" class="progress-display" :auto-start="true" />
        <Vue3Lottie :animationData="loadingJson" height="506" width="336" class="json-lot" />
        <ShinyText text="​​Generating ...​" :disabled="false" :speed="3" class-name="shiny-text" />
      </div>
    </div>

    <!-- 列表区域 -->
    <div class="tpls">
      <div
        v-for="item in templateItems"
        :key="item.template_id"
        class="item"
        :class="{ active: item.template_id === formData.template_id }"
        @click.stop="selectItem(item.template_id)">
        <!-- 第一行：图片 -->
        <div class="image-container">
          <img :src="item.img" :alt="item.name" class="item-image" />
        </div>
        <!-- 第二行：name -->
        <div class="name">
          {{ item.title }}
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <button class="btn btn-secondary" :disabled="isSubmitting" @click="handleSubmit">
        Regenerate
      </button>
      <button
        class="btn btn-primary"
        :disabled="isSubmitting || taskDetail.status !== TaskType.SUCCESS"
        @click="handleSubmitFrame">
        View Frame Styles
      </button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { QShopAPI, QShopType } from '@/api/qshop';
  import router from '@/router/route';
  import { computed, onMounted, onUnmounted, ref } from 'vue';
  import ShinyText from '@/components/basic/ShinyText.vue';
  import { Vue3Lottie } from 'vue3-lottie';
  import loadingJson from '@/assets/lottie/loading_bg.json';
  import { TaskType } from '@/types/ai';
  import { showToast } from 'vant';
  import ProgressNumber from '../components/ProgressNumber.vue';
  import { useUserStore } from '@/store/user';
  import { useLoginModal } from '@/composables/useLoginModal';

  const taskId = ref((router.currentRoute.value.query.task_id as string) || '');
  const taskDetail = ref<any>({});

  // 图片URL
  const imageUrl = computed(() => (taskDetail.value?.result_imgs?.[0] || {}).img_url || '');

  // 表单数据模型
  const formData = ref({
    type: QShopType.EDIT,
    template_id: 0,
    prompt: '',
  });

  const templateItems = ref<any>([]);

  // 提交状态和任务状态
  const isSubmitting = ref(false);

  // 保存轮询的timer ID
  const pollTimer = ref<number | null>(null);

  // 进度组件引用
  const progressComponent = ref<InstanceType<typeof ProgressNumber> | null>(null);

  // 图片URL
  const cropUrl = decodeURIComponent((router.currentRoute.value.query.cropUrl as string) || '');

  // 返回
  const goBack = () => {
    router.back();
  };

  // 选择项
  const selectItem = (id: number) => {
    formData.value.template_id = id;
  };

  // 加载分类数据
  const loadCategories = async () => {
    const response = await QShopAPI.getFilterCategorys({});
    templateItems.value = response.data.map((item: any) => ({
      ...item,
      template_id: item.id,
    }));
    formData.value.template_id = Number(router.currentRoute.value.query.template_id || 0);
  };

  // 处理表单提交
  const handleSubmit = async () => {
    if (isSubmitting.value) return;
    if (!cropUrl) return;

    try {
      isSubmitting.value = true;

      const prompt_text =
        templateItems.value.find((item: any) => item.template_id === formData.value.template_id)
          ?.prompt_text || '';
      const params = {
        gen_type: formData.value.type,
        template_id: formData.value.template_id,
        prompt_text: prompt_text,
        img: cropUrl,
      };

      const res = await QShopAPI.generate(params);
      taskId.value = res.data.task_id || '';
      // 同步更新路由参数中的task_id
      router.replace({
        query: {
          ...router.currentRoute.value.query,
          task_id: taskId.value,
        },
      });
      checkTaskStatus();
    } catch (error: any) {
      const { code } = error.response.data || {};
      if (code === 100201) {
        showToast('One task at a time, please wait until the current task is finished');
      }
      isSubmitting.value = false;
    }
  };

  // 查询任务状态
  const checkTaskStatus = async () => {
    if (!taskId.value) return;

    // 先清除之前可能存在的timer，防止多个timer同时运行
    if (pollTimer.value) {
      clearTimeout(pollTimer.value);
      pollTimer.value = null;
    }

    const params = {
      task_id: taskId.value,
    };
    const res = await QShopAPI.generateTaskDetail(params);

    taskDetail.value = res.data;
    if (res.data.status === TaskType.PROCESSING) {
      // 任务开始，继续查询
      pollTimer.value = window.setTimeout(() => {
        checkTaskStatus();
      }, 3000);
      isSubmitting.value = true;
    } else {
      isSubmitting.value = false;
    }
  };

  // 处理相框表单提交
  const isSubmittingFrame = ref(false);
  const handleSubmitFrame = async () => {
    if (isSubmittingFrame.value || !imageUrl.value) return;
    isSubmittingFrame.value = true;
    const params = {
      gen_type: QShopType.PHOTO,
      img: imageUrl.value,
    };
    const res = await QShopAPI.generate(params);
    taskId.value = res.data.task_id || '';
    router.push({
      name: 'ActivityPhotoframeFrame',
      query: {
        task_id: taskId.value,
      },
    });
    isSubmittingFrame.value = false;
  };

  onMounted(() => {
    loadCategories();
    if (taskId.value) {
      checkTaskStatus();
    }

    setTimeout(() => {
      onLoginDialogOpen();
    }, 3000);

    setVh();
  });

  function setVh() {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
  }

  // 组件卸载时清除轮询
  onUnmounted(() => {
    if (pollTimer.value) {
      clearTimeout(pollTimer.value);
      pollTimer.value = null;
    }
  });

  // 打开登录弹窗
  const userStore = useUserStore();
  const isLoggedIn = computed(() => userStore.isAuthenticated);
  const onLoginDialogOpen = () => {
    const { showModal } = useLoginModal();
    if (!isLoggedIn.value) {
      showModal();
    }
  };
</script>

<style scoped lang="scss">
  // 基础样式
  .page {
    height: 100vh;
    height: 100dvh;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    padding-top: 56px;
    padding-bottom: env(safe-area-inset-bottom, 0);
  }
  .head {
    padding: 8px 16px 0 16px;
  }
  .preview {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    // padding: 0 16px;
    position: relative;
    img {
      width: 100%;
    }

    .error {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      img {
        width: 64px;
        margin-bottom: 16px;
      }
      p {
        font-size: 16px;
        font-weight: 400;
        color: #7a7a7a;
      }
    }
    .loading-place {
      position: absolute;
      // border-radius: 8px;
      overflow: hidden;
      width: 100%;
      height: 100%;
      bottom: 0;
      left: 0;
      right: 0;
      .shiny-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #7a7a7a;
        white-space: nowrap;
        font-size: 18px;
        font-weight: 400;
        height: 20px;
        line-height: 20px;
      }
      .progress-display {
        position: absolute;
        top: 16px;
        left: 16px;
      }
      .json-lot {
        margin: 0 auto;
        max-width: 100%;
        height: auto;
        display: block;
      }
    }
  }

  .tpls {
    display: inline-flex;
    overflow-x: auto;
    gap: 8px;
    padding: 16px 16px;
    padding-bottom: 0;
    scrollbar-width: none; // Firefox
    min-height: 109px;
    &::-webkit-scrollbar {
      display: none; // Chrome, Safari, Edge
    }
    .item {
      cursor: pointer;
      border-radius: 8px;
      text-align: center;

      height: 100%;
      box-sizing: border-box;
      &.active {
        .name {
          color: #f76b1b;
        }
        .image-container {
          border-color: #f76b1b;
          &:hover {
            border-color: #f76b1b;
          }
        }
      }

      .image-container {
        width: 72px;
        height: 72px;
        overflow: hidden;
        border-radius: 8px;
        background-color: #f8f8f8;
        flex-shrink: 0;
        border: 2px solid transparent;
        margin-bottom: 4px;

        .item-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      .name {
        font-size: 12px;
        font-weight: 500;
        color: #aaa;
      }
    }
  }

  .bottom-buttons {
    display: flex;
    gap: 16px;
    padding: 16px 16px;
    .btn-primary {
      flex: 1;
      height: 40px;
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      background: #f76b1b;
      padding: 0px 20px;
      &:disabled {
        opacity: 0.5;
        pointer-events: none;
      }
      &:active:not(:disabled) {
        opacity: 0.9;
      }
    }
    .btn-secondary {
      height: 40px;
      color: #f76b1b;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      background: #fbe6db;
      padding: 0px 20px;
      &:disabled {
        opacity: 0.5;
        pointer-events: none;
      }
      &:hover:not(:disabled) {
        opacity: 0.9;
      }
    }
  }
</style>
